package isquirrel;

import isquirrel.beans.UserInterest;
import isquirrel.recommender.StaticRecommender;
import isquirrel.util.HibernateUtil;

public class RecWorker extends Thread{
	
	private volatile boolean _threadstop = false;
	
	@Override
	public void run() {
		
		QueuePool.addQueue("rec", UserInterest.class);
		
		int sleeptime = 20;
		while (!_threadstop){
			
			UserInterest ui = null;
			try{
				if (QueuePool.getQueue("rec").size() > 0){
					ui = (UserInterest) QueuePool.getQueue("rec").remove();
				}
			}
			catch(Exception e){	
				ui = null;
			}
			
			if (ui != null){
				
				sleeptime = 40;
				
				HibernateUtil.beginTransaction();
//				System.out.println("Adding static recommendations..");
				StaticRecommender.insertRecommendations(ui.user(), ui.interest());
				HibernateUtil.commit();
				
			}
			else {
				sleeptime += 4;
				if (sleeptime > 200){
					sleeptime = 200;
				}
			}
			
			try {
				Thread.sleep(sleeptime);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
	
	}
	
	public void stopThread(){
		_threadstop = true;
	}
	
	
}
